package io.github.wjehovah.yyn.adapter;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.util.List;
import java.util.concurrent.ExecutorService;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import io.github.wjehovah.yyn.App;
import io.github.wjehovah.yyn.CommentActivity;
import io.github.wjehovah.yyn.R;
import io.github.wjehovah.yyn.activity.profile.PersonalProfileActivity;
import io.github.wjehovah.yyn.bean.CommBean.BeanDetail;
import io.github.wjehovah.yyn.data.Budejie;

/**
 * Created by lcy
 */
public class TypedListAdapter extends BaseAdapter implements View.OnClickListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener {


//    private List<VideoInfo> videoList=new ArrayList<VideoInfo>();
//    private VideoView mVideoView;

    private int currentIndex = -1;
    private int playPosition = -1;
    private boolean isPaused = false;
    private boolean isPlaying = false;

    public static final int VIDEO = 0;
    public static final int IMG = 1;
    public static final int JOKE = 2;
    public static final String DING = "love";
    public static final String CAI = "cai";
    public static final String FORWARD = "forward";
    public static final String JUBAO = "jubao";

    private Bundle bd = new Bundle();
    private Intent intent;
    private Context mContext;
    private LayoutInflater mInflater;
    private List<BeanDetail> data;
    private BitmapUtils bitmapUtils;

    private HttpUtils httpUtils;

    // private BeanDetail beanDetail;

    private ViewHolder holder1;
    private MediaController mMediaCtrl;
    private ExecutorService executorService;
    private int playVoicePosition = -1;
    private boolean isPlayingVoice = false;
    private MediaPlayer mediaPlayer;
    private Uri uri;


    public TypedListAdapter(Context mContext, List<BeanDetail> data) {
        this.mContext = mContext;
        this.mInflater = LayoutInflater.from(mContext);
        this.data = data;

        bitmapUtils = new BitmapUtils(App.getContext(), "", 0.6f, 1024 * 1024 * 6);
        httpUtils = new HttpUtils(1000);
    }

    /**
     * String DONG_URL = "http://api.budejie.com/api/api_open.php?a=cai&c=data";
     * &dong=cai&tj_from=image&id=
     */
    private String getType(BeanDetail beanDetail) {
        String type = "";
        if (beanDetail.type.equals(Budejie.TYPE_VIDEO + "")) {
            type = "video";
        } else if (beanDetail.type.equals(Budejie.TYPE_IMG + "")) {
            type = "image";
        } else if (beanDetail.type.equals(Budejie.TYPE_DUANZI + "")) {
            type = "text";
        }
        return type;
    }

    private String getUrl(String action, BeanDetail beanDetail) {
        String type = getType(beanDetail);
        String url = "";
        if (action.equals(DING) || action.equals(CAI)) {
            url = Budejie.DONG_URL + "&dong=" + action + "&tj_from=" + type + "&id=" + beanDetail.id;
        }
        return url;
    }

    /**
     * 这个方法 是分类型ListView Item Layout 的总数
     */
    @Override
    public int getViewTypeCount() {
        return Budejie.TYPE;
    }


    /**
     * 根据传入的Position 获得当前ItemView 的Type
     *
     * @param position 当前ListView Item的位置
     */
    @Override
    public int getItemViewType(int position) {
        String type = data.get(position).type;
        int i = Integer.parseInt(type);
        switch (i) {
            case Budejie.TYPE_VIDEO:
                return Budejie.ID_OF_VIDEO;
            case Budejie.TYPE_IMG:
                return Budejie.ID_OF_IMG;
            case Budejie.TYPE_DUANZI:
                return Budejie.ID_OF_JOKE;
            default:
                return Budejie.ID_OF_VOICE;
        }
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public BeanDetail getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        int type = getItemViewType(position);
        final int mPosition = position;
        final ViewHolder holder;


        if (convertView == null) {
            holder = new ViewHolder();
            //公用的容器
            convertView = mInflater.inflate(R.layout.post_item_layout, null);
            RelativeLayout rl = (RelativeLayout) convertView;
            LinearLayout post_container = (LinearLayout) rl.findViewById(R.id.post_container);

            switch (type) {
                case Budejie.ID_OF_IMG://图片

                    ImageView image = (ImageView) mInflater.inflate(R.layout.item_list_image_content, null);
                    image.setScaleType(ImageView.ScaleType.CENTER_INSIDE);


                    post_container.addView(image, 2);

                    initViewHolder(holder, post_container);
                    holder.contentImg = (ImageView) post_container.findViewById(R.id.iv_content);//内容图片


                    break;
                case Budejie.ID_OF_JOKE://段子
                    initViewHolder(holder, post_container);
                    break;

                case Budejie.ID_OF_VIDEO://视频
                    View video = mInflater.inflate(R.layout.content_item, null);
                    post_container.addView(video, 2);
                    initViewHolder(holder, post_container);
                    holder.video = (VideoView) video.findViewById(R.id.video);//VideoView
                    Log.e("LCY", "//VideoView=" + holder.toString());
                    holder.video.setTag(getItem(position).videouri);//设置url为标志；
                    holder.image_small = (ImageView) video.findViewById(R.id.iv_small);//视频缩略图
                    holder.play = (ImageView) video.findViewById(R.id.iv_play);//播放按钮
                    holder.play.setTag(position);
                    holder.playcount = (TextView) video.findViewById(R.id.tv_videocount);//视频次数
                    holder.videotime = (TextView) video.findViewById(R.id.tv_videotime);//视频时间
                    holder.mProgressBar = (ProgressBar) video.findViewById(R.id.progressBar);//progressBar

                    initViewHolder(holder, post_container);


                    break;
                case Budejie.ID_OF_VOICE:
                    View voice = mInflater.inflate(R.layout.item_voice, null);
                    post_container.addView(voice, 2);
                    initViewHolder(holder, post_container);
                    holder.contentImg = (ImageView) post_container.findViewById(R.id.iv_content_last);//内容图片
                    holder.playVoice = (ImageView) post_container.findViewById(R.id.iv_play_voice);//播放声音图片；；
                    holder.content.setTag(getItem(position).voiceuri);//设置声音url为标志；
                    break;
            }
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        final BeanDetail beanDetail = getItem(position);
        Log.e("ding", beanDetail.type);

        holder.usericon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, PersonalProfileActivity.class);
                intent.putExtra(Budejie.PROFILE, beanDetail);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }
        });
        holder.love.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = getUrl(DING, beanDetail);
                setDongStatus(url, beanDetail, DING);
            }
        });
        holder.hate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = getUrl(CAI, beanDetail);
                Log.e("ding", url);
                setDongStatus(url, beanDetail, CAI);
            }
        });

        holder.comment.setTag(position);
        if (holder.play != null) {//播放按钮监听；；
            holder.play.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    playVideo(mPosition, holder, beanDetail);//开始播放视频。传入的是位置，url等；
                    Log.e("LCY", "// playVide=" + holder.toString());
                }


            });//播放设置监听；
        }
        if (holder.playVoice != null) {
            holder.playVoice.setOnClickListener(new View.OnClickListener() {//播放声音监听；；；
                @Override
                public void onClick(View v) {
                    playVoicePosition=position;
                    isPlayingVoice=!isPlayingVoice;
                    playOrStopVoice(position, holder);//播放声音；；；

                }
            });
        }
        holder.comment.setOnClickListener(this);//评论设置监听；
        switch (type) {
            case Budejie.ID_OF_IMG:

                bitmapUtils.display(holder.usericon, beanDetail.profile_image);//用户名头像；

                holder.username.setText(beanDetail.screen_name);//用户名
                holder.passtime.setText(beanDetail.created_at);//时间
                holder.content.setText(beanDetail.text);//内容

//            Glide.with(mContext).load(beanDetail.image1).centerCrop().placeholder(R.drawable.loading).crossFade().into(holder.contentImg);
                Glide.with(mContext).load(beanDetail.image1).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(holder.contentImg);
                holder.love.setText(beanDetail.love);//顶
                holder.hate.setText(beanDetail.hate);//踩
                holder.forward.setText(beanDetail.repost);//分享
                holder.comment.setText(beanDetail.comment);//评论
                break;
            case Budejie.ID_OF_JOKE:
                bitmapUtils.display(holder.usericon, beanDetail.profile_image);//用户名头像；

                holder.username.setText(beanDetail.screen_name);//用户名
                holder.passtime.setText(beanDetail.created_at);//时间
                holder.content.setText(beanDetail.text);//内容
                holder.love.setText(beanDetail.love);//顶
                holder.hate.setText(beanDetail.hate);//踩
                holder.forward.setText(beanDetail.repost);//分享
                holder.comment.setText(beanDetail.comment);//评论
                break;

            case Budejie.ID_OF_VIDEO:
                //设置用户名
                holder.username.setText(beanDetail.screen_name);
                //设置发表时间
                holder.passtime.setText(beanDetail.passtime);
                //设置内容
                holder.content.setText(beanDetail.text);
                holder.playcount.setText("播放次数：" + beanDetail.playcount);
                holder.videotime.setText(beanDetail.videotime + "秒");

                holder.video.setVisibility(View.GONE);
                bitmapUtils.display(holder.image_small, beanDetail.image_small);
                //设置点赞
                holder.love.setText(beanDetail.love);
                //设置踩
                holder.hate.setText(beanDetail.hate);
                //设置转发  //数据存在问题  没有转发
                holder.forward.setText(beanDetail.favourite);
                //设置评论
                holder.comment.setText(beanDetail.comment);
                break;
            case Budejie.ID_OF_VOICE:
//                ,,记录position，若是播放设置暂停图片；；
                if (position == playVoicePosition && isPlayingVoice) {//当前正在播放音频，并且当前的position等于播放的position；；
                    holder.playVoice.setImageResource(R.drawable.icon_pause);//音频暂停按钮；；
                } else {
                    holder.playVoice.setImageResource(R.drawable.icon_play);//音频播放按钮；；
                }
                bitmapUtils.display(holder.usericon, beanDetail.profile_image);//用户名头像；
                holder.username.setText(beanDetail.screen_name);//用户名
                holder.passtime.setText(beanDetail.created_at);//时间
                holder.content.setText(beanDetail.text);//内容
                holder.content.setTag(beanDetail.voiceuri);//设置声音的url为标志；
                bitmapUtils.display(holder.contentImg, beanDetail.image1);//内容图片；
                holder.love.setText(beanDetail.love);//顶
                holder.hate.setText(beanDetail.hate);//踩
                holder.forward.setText(beanDetail.repost);//分享
                holder.comment.setText(beanDetail.comment);//评论
                break;
            default:
                bitmapUtils.display(holder.usericon, beanDetail.profile_image);//用户名头像；

                holder.username.setText(beanDetail.screen_name);//用户名
                holder.passtime.setText(beanDetail.created_at);//时间
                holder.content.setText(beanDetail.text);//内容
                bitmapUtils.display(holder.contentImg, beanDetail.image1);//内容图片；
                holder.love.setText(beanDetail.love);//顶
                holder.hate.setText(beanDetail.hate);//踩
                holder.forward.setText(beanDetail.repost);//分享
                holder.comment.setText(beanDetail.comment);//评论
                break;
        }
        //给转发设置监听
        holder.forward.setOnClickListener(this);

        return convertView;

    }

    private void playOrStopVoice(final int position, final ViewHolder holder) {//异步任务请求播放网络音频；；
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected void onPreExecute() {
                String voiceUrl = (String) holder.content.getTag();
                Log.e("LCy", "服务==voiceUrl==" + voiceUrl);
                uri = Uri.parse(voiceUrl);
                if (playVoicePosition == position && isPlayingVoice) {
                    holder.playVoice.setImageResource(R.drawable.icon_pause);
                } else {
                    holder.playVoice.setImageResource(R.drawable.icon_play);
                }

            }

            @Override
            protected Void doInBackground(Void... params) {
                if (isPlayingVoice){
                    if (mediaPlayer == null) {
                        mediaPlayer = MediaPlayer.create(mContext, uri);
                    }
                    mediaPlayer.start();
                }else {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    mediaPlayer = null;
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                if (mediaPlayer==null){
                    return;
                }
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        isPlayingVoice=false;
                        holder.playVoice.setImageResource(R.drawable.icon_play);
                    }
                });
            }
        }.execute();
    }

    private void initViewHolder(ViewHolder holder, LinearLayout post_container) {
        holder.usericon = (ImageView) post_container.findViewById(R.id.writerProfile);//用户头像
        holder.username = (TextView) post_container.findViewById(R.id.writerName);//用户名
        holder.passtime = (TextView) post_container.findViewById(R.id.addtime);//审核通过时间
        holder.itemMore = (ImageButton) post_container.findViewById(R.id.itemMore);//内容
        holder.content = (TextView) post_container.findViewById(R.id.content);//内容
        holder.love = (TextView) post_container.findViewById(R.id.dingCount);//顶
        holder.hate = (TextView) post_container.findViewById(R.id.caiCount);//踩
        holder.forward = (TextView) post_container.findViewById(R.id.forwardCount);//分享
        holder.comment = (TextView) post_container.findViewById(R.id.commentCount);//评论
    }

    private void playVideo(int position, ViewHolder holder, BeanDetail beanDetail) {

        holder.image_small.setVisibility(View.GONE);//视频缩略图
        holder.play.setVisibility(View.GONE);//播放按钮
        holder.playcount.setVisibility(View.GONE);//视频次数
        holder.videotime.setVisibility(View.GONE);//视频时间

        holder.video.setVisibility(View.VISIBLE);//VideoView
        mMediaCtrl = new MediaController(mContext, false);
        mMediaCtrl.setAnchorView(holder.video);
        mMediaCtrl.setMediaPlayer(holder.video);
        holder.video.setMediaController(mMediaCtrl);
        holder.video.requestFocus();
//        holder.mProgressBar.setVisibility(View.VISIBLE);
        BeanDetail beanDetail11 = getItem(position);//重新获取url
        holder.video.setVideoURI(Uri.parse(beanDetail11.videouri));////传入的url错位；；；；；
        holder.video.start();
        Log.e("LCY", "holder.video.start();");
        setHolder(holder);
        Log.e("LCY", "setHolder(holder);");
    }

    public void setHolder(ViewHolder holder) {
        this.holder1 = holder;
    }

    public ViewHolder getHolder1() {
        return holder1;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.commentCount:
                int position = (int) v.getTag();
                BeanDetail beanDetail = data.get(position);
                intent = new Intent(mContext, CommentActivity.class);
                bd.putParcelable("beanDetail", beanDetail);//
                intent.putExtras(bd);
                mContext.startActivity(intent);
                break;
//            case R.id.iv_play:
//                break;

            case R.id.forwardCount:
                Toast.makeText(mContext, "转发", Toast.LENGTH_SHORT).show();

                showShare();

                break;
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {

    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        return false;
    }


    public static class ViewHolder {
        public ImageView usericon;
        public ImageView playVoice;
        public TextView username;
        public TextView passtime;
        public TextView content;
        public TextView love;
        public TextView hate;
        public TextView forward;
        public TextView comment;
        public ImageView contentImg;
        public VideoView video;

        public ImageView play;
        public TextView playcount;//   17
        public TextView videotime;//     43
        public ImageView image_small;//     http://wimg.spriteapp.cn/picture/2015/0811/55c9af64ac4f8_wpd.jpg
        public ProgressBar mProgressBar;
        public ImageButton itemMore;
    }

    public MediaController getmMediaCtrl() {
        return mMediaCtrl;
    }

    private void setDongStatus(String url, final BeanDetail beanDetail, final String action) {
        httpUtils.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                if (!responseInfo.result.equals("0")) {
                    if (action.equals(DING) && !beanDetail.dong) {
                        beanDetail.love = Integer.valueOf(beanDetail.love) + 1 + "";
                        beanDetail.dong = true;
                        notifyDataSetChanged();
                    } else if (action.equals(CAI) && !beanDetail.dong) {
                        beanDetail.hate = Integer.valueOf(beanDetail.hate) + 1 + "";
                        beanDetail.dong = true;
                        notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
            }
        });
    }

/*    public BeanDetail getBeanDetail() {
        return beanDetail;
    }*/


    /**
     * 转发分享
     */


    private void showShare() {
        ShareSDK.initSDK(mContext);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));

        // text是分享文本，所有平台都需要这个字段
        oks.setText("you");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片

        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");


        // 启动分享GUI
        oks.show(mContext);
    }
}
